import React from 'react';
import {Terminal} from "xterm";
import "xterm/css/xterm.css";
import "xterm/lib/xterm.js";
import styles from './index.module.scss';


class ServerManageSSH extends React.Component {
    constructor(props) {
        super(props);
        this.state = {};

        this.term = null;
        this.client = null;
        this.selection = "";
        this.connect = this.connect.bind(this);
    }

    /**
     * 加载进来的时候执行
     */
    componentDidMount() {
        const params = new URLSearchParams(this.props.location.search);
        const id = params.get('id');
        const name = params.get('name');
        document.title = "远程操作-" + name;
        let terminalContainer = document.getElementById('terminal-container');
        const rows = document.querySelector(".indexContainer").offsetHeight / 16 - 5;
        const cols = document.querySelector(".indexContainer").offsetWidth / 9;
        this.term = new Terminal({
            rendererType: "canvas", //渲染类型
            pid: 1,
            name: 'terminal',
            rows: parseInt(rows), //行数
            cols: parseInt(cols),
            convertEol: true, //启用时，光标将设置为下一行的开头
            scrollback: 500000,//终端中的回滚量
            disableStdin: false, //是否应禁用输入。
            cursorStyle: 'underline', //光标样式
            cursorBlink: true, //光标闪烁
            tabStopWidth: 8, //制表宽度
            screenKeys: true, //Xterm下的快捷键
            logLevel: "debug",
            theme: {
                foreground: '#58a6ff', //字体,LightGreen,Orange,SlateBlue,Magenta Purple Red Violet White Yellow
                background: '#2B2B2B', //背景色
                frontSize: 12,
                cursor: "Orange", //设置光标
                lineHeight: 12
            }
        });
        this.term.write('Hello from \x1B[1;3;31mxterm.js\x1B[0m $ ');
        // 换行并输入起始符“$”
        this.term.prompt = () => {
            this.term.write("\r\n$ ");
        };
        this.term.open(terminalContainer);
        this.client = new WebSocketClient();
        //选中复制
        this.term.onSelectionChange(function () {
            // if (this.term.hasSelection()) {
            //     this.selection = this.term.getSelection();
            // }
        });
        this.term.attachCustomKeyEventHandler(function (ev) {
            //粘贴 ctrl+v
            if (ev.keyCode === 86 && ev.ctrlKey) {
                this.client.sendClientData("\x00" + this.selection);
                this.selection = "";
            }
        });
        window.addEventListener("resize", () => {
            this.term.scrollToBottom();
            try {
                // fitAddon.fit();
                // 窗口大小改变时触发xterm的resize方法，向后端发送行列数，格式由后端决定
                this.term.onResize(size => {
                    this.client.send({Op: "resize", Cols: cols, Rows: rows});
                });
            } catch (e) {
                console.log("e", e.message);
            }
        });
        this.connect({
            id: id
        }, "terminal-container");
    }

    /**
     * 连接
     * @param params
     * @param divId
     */
    connect = (params) => {
        const that = this;
        //在页面上显示连接中...
        this.term.write('\r\nConnecting...');
        //执行连接操作
        this.client.connect({
            onError: function (error) {
                //连接失败回调
                that.term.write('Error: ' + error + '\r\n');
            },
            onConnect: function () {
                //连接主机
                that.client.send(params);

            },
            onClose: function () {
                //连接关闭回调
                that.term.write("\rconnection closed");
            },
            onData: function (data) {
                //收到数据时回调
                that.term.write(data);
            }
        });
        that.term.onData(e => {
            //键盘输入时的回调函数
            that.client.sendClientData(e);
        })
    };
    /**
     * 在渲染前调用,在客户端也在服务端
     */
    componentWillMount = () => {

    };


    render() {
        return (
            <div id="terminal-container" className="indexContainer"/>
        );
    }
}

export default ServerManageSSH;
